package com.adminsystem.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.adminsystem.entity.custom.EchartsBean;
import com.adminsystem.entity.custom.Result;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/app/map")
public class AppController {
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('app:echarts:map')")
    public Result getMEchartsData(@RequestBody EchartsBean echartsBean) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", "application/json");
        headers.set("Content-Type", "application/json");
        ResponseEntity<String> response = restTemplate.exchange(echartsBean.getUrl(), HttpMethod.GET, null, String.class, headers);
        String result = response.getBody();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return Result.success(jsonObject);
    }

    @GetMapping("/search")
    public Result getMapSearchData(@RequestParam String query, @RequestParam String region) {
        String ak = "e9s1lF6wsobNnIu5ldVUxyy4DV7PAgUH";
        String url = "https://api.map.baidu.com/place/v2/suggestion?query={}&region={}&city_limit=true&output=json&ak={}";
        url = StrUtil.format(url, query, region, ak);
        //发起请求
        String body = HttpRequest.get(url).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        return Result.success(jsonObject.get("result"));
    }
}
